﻿using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Newtonsoft.Json;
using System.Text;

namespace Infrastructure.EntityConfigs
{
    public class BaseEntityConfig<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : BaseEntity
    {
        public virtual void Configure(EntityTypeBuilder<TEntity> builder)
        {
            builder.ToTable(GetTableName(typeof(TEntity).Name));

            builder.HasKey(b => b.Id);
            builder.Property(b => b.Id).ValueGeneratedNever();
            builder.Property(b => b.CreateTime).HasColumnType("datetime");
            builder.Property(b => b.UpdateTime).HasColumnType("datetime");
        }

        private string GetTableName(string entityName)
        {
            var tableName = new StringBuilder().Append(ConstKeyNames.MoudleId);

            foreach (var charItem in entityName)
            {
                if (charItem is >= 'A' and <= 'Z')
                    tableName.Append("_").Append((char)(charItem + 32));
                else
                    tableName.Append(charItem);
            }

            return tableName.Append("s").ToString();
        }

        protected static string ToStr<TData>(TData item, TData defaultVal)
        {
            item ??= defaultVal;
            return JsonConvert.SerializeObject(item);
        }
        protected static TData? ToObj<TData>(string str, TData? defaultVal)
        {
            if (string.IsNullOrEmpty(str)) return defaultVal;

            return JsonConvert.DeserializeObject<TData>(str);
        }
    }
}
